<template>
<!-- 项目集添加或编辑   -->
    <div>
        <el-steps v-if="!disabled" :active="state.active" align-center>
            <el-step title="项目基本信息" />
            <el-step title="完成" />
        </el-steps>

        <el-form
                v-if="!state.success"
                :model="formInline"
                ref="formInlineRef"
                :rules="projectRules"
                class="demo-form-inline m-t20"
                label-width="120px"
                :disabled="disabled"
        >
            <div class="twoline">
                <el-form-item label="项目集名称" prop="projectSetName">
                    <el-input
                            v-model="formInline.projectSetName"
                            placeholder="项目集名称"
                    />
                </el-form-item>
                <el-form-item label="编号" prop="projectSetCode">
                    <el-input
                            v-model.number="formInline.projectSetCode"
                            placeholder="编号"
                    />
                </el-form-item>
            </div>
            <div class="twoline">
                <el-form-item label="项目位置" prop="address">
                    <el-input v-model="formInline.address" placeholder="项目位置">
                        <template #append
                        ><svg-icon
                                icon-class="map-icon"
                                style="cursor: pointer"
                                class="refresh-icon m-l10"
                                @click="mapclick"
                        /></template>
                    </el-input>
                </el-form-item>

                <el-form-item label="所属街道" prop="streetCode">
                    <el-select
                            v-model="formInline.regionCode"
                            clearable
                            placeholder="请选择区域"
                            @change="areaTypeChange"
                    >
                        <el-option
                                v-for="item in state.areaTypeOptionsArr"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                        />
                    </el-select>
                    <el-select
                            v-model="formInline.streetCode"
                            clearable
                            placeholder="请选择街道"
                            @change="streerTypeChange"
                    >
                        <el-option
                                v-for="item in state.streerTypeOptionsArr"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                        />
                    </el-select>
                </el-form-item>
            </div>
            <div class="twoline">
                <el-form-item label="项目(可多选)" class="oneline" prop="projects">
                    <el-select
                            v-model="formInline.projects"
                            clearable
                            class="select_project"
                            multiple
                            placeholder="请选择项目"
                            @change="changeProject"
                    >
                        <el-option
                                v-for="item in state.projectOptionsArr"
                                :key="item.projectId"
                                :label="item.projectName"
                                :value="item.projectId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目总额" prop="projectInvestmentAmount">
                    <el-input
                            v-model="formInline.projectInvestmentAmount"
                            placeholder="项目总额"
                    />
                </el-form-item>
            </div>

            <el-form-item label="备注" class="oneline" prop="remark">
                <el-input v-model="formInline.remark" :rows="5"  maxlength="500" show-word-limit type="textarea" />
            </el-form-item>
        </el-form>

        <div class="buttons" v-if="!state.success">
            <el-button @click="goback">{{disabled?'关闭':'取消'}}</el-button>
            <el-button v-if="!disabled" type="primary" @click="submitHandler()">
                确定
            </el-button>
        </div>
        <div v-if="state.success">
            <p style="height: 40px">
                <svg-icon
                        icon-class="sucesss-icon"
                        style="width: 100%; height: 100%"
                ></svg-icon>
            </p>
            <p style="font-size: 16px; text-align: center">
                {{ `恭喜您，完成项目集的${ type==='update' ? '编辑' : '添加'}!` }}
            </p>
            <p style="font-size: 16px; text-align: center">
                <el-button @click="goback">返回列表页</el-button>
            </p>
        </div>
        <mapDialog ref="mapdialog" @getMapAddrInfo="getMapAddrInfo"></mapDialog>
    </div>
</template>
<script setup>
import MapDialog from '@/views/constructionProjectManage/projectmanagement/components/mapDialog.vue';
import { ref, reactive, onMounted, computed } from 'vue'
import { assetsApi } from '@/api/assets'
import { useRouter, useRoute } from 'vue-router'
import { projectApi, projectListApi } from '@/api/project'
import {projectSetApi} from "@/api/investment";
import {
    ElForm,
    ElSelect,
    ElFormItem,
    ElStep,
    ElSteps
} from 'element-plus'

const state = reactive({
    streerTypeOptionsArr: [],
    areaTypeOptionsArr: [],
    projectOptionsArr: [], //所有项目
    editId: '', //编辑时ID
    active: 1,
    success: false, //编辑或添加是否成功
    type: 0 //0新增 1编辑
});

//路由跳转
let router = useRouter()
let route = useRoute()
const type = router.currentRoute.value.params.type;
const id = router.currentRoute.value.params.id;
const disabled = ref(type==='query'?true:false);

let centerDialogVisible = ref(false)
let formInlineRef = ref(null)
const formInline = reactive({
    projects: [],
    address: '',
    remark: ''
})

const projectRules = reactive({
    projectSetName: [
        { required: true, message: '项目集名称不能为空', trigger: 'blur' }
    ],
    projectSetCode: [
        { required: true, message: '编号不能为空', trigger: 'blur' }
    ],
    streetCode: [
        { required: true, message: '所属街道不能为空', trigger: 'blur' }
    ],
    projectInvestmentAmount: [{ required: true, message: '项目总额不能为空', trigger: 'blur' }]
})
const mapdialog = ref(null)
const mapclick = () => {
    if(disabled.value)return;
    if (mapdialog?.value) {
        mapdialog.value.openMap()
    }
}
const getMapAddrInfo = (data) => {
    formInline.address = data.address
}

// 初始化获取区域
const initAreaOptions = (type, cd) => {
    assetsApi.getLocations(type, cd).then((res) => {
        const { code, data, msg } = res
        if (code == 200) {
            if (cd) {
                state.streerTypeOptionsArr = data
            } else {
                state.areaTypeOptionsArr = data
            }
        }
    })
}
//获取所有项目信息
const projectListApiHandler = () => {
    let obj = {
        projectSetId: ''
    }
    projectListApi.getAllList(obj.projectSetId).then((res) => {
        const { code, data, msg } = res
        if (code == 200) {
            state.projectOptionsArr = data

        }
    })
}
//区域变化
const areaTypeChange = (val) => {
    state.areaTypeOptionsArr.forEach((item) => {
        if (item.code == val) {
            formInline.regionName = item.name
        }
    })
    initAreaOptions(2, val)
}
//街道变化
const streerTypeChange = () => {
    state.streerTypeOptionsArr.forEach((item) => {
        if (item.code == formInline.streetCode) {
            formInline.streetName = item.name
        }
    })
}
//项目多选下拉变化
const changeProject = (val) => {
    console.log(val)
}

/**
 * 新增或编辑的提交
 */
const submitHandler = () => {
    formInlineRef.value.validate((valid, fields) => {
        if (valid) {
            let submitObj = JSON.parse(JSON.stringify(formInline))
            let projects = []
            submitObj.projects.forEach((item) => {
                let itemObj = state.projectOptionsArr.filter(
                    (e) => e.projectId == item
                )[0]

                projects.push(itemObj)
            })
            submitObj.projects = projects
            submitObj.projectSetId = submitObj.projectSetId || '';
            projectSetApi[type](submitObj).then(res=>{
                const { code, data, msg } = res
                if (code == 200) {
                    state.success = true
                    state.active = 2
                }
            });
        }
    })
}
//返回列表页
const goback = () => {
    router.push({
        path: '/investmentProjectManagement/preparatoryProject/programManagement'
    })
}

/**
 * 根据项目集id获取详情
 * @param id
 */
const getByIdHandler = (id) => {
    projectSetApi.getProjectSet({projectSetId:id}).then(res=>{
        const { code, data, msg } = res;
        if (code == 200) {
            if (data?.projects) {
                let arr = []
                data.projects.forEach((item) => {
                    arr.push(item.projectId)
                })
                data.projects = arr
            }

            initAreaOptions(2, data.regionCode)
            setTimeout(() => {
                Object.assign(formInline, data)
            }, 0)
        }
    });
}

onMounted(() => {
    initAreaOptions(1); //获取区域街道信息
    projectListApiHandler();

    //编辑
    if (type === 'update' || type === 'query') {
        getByIdHandler(id)
    }
})
</script>
<style lang="scss" scoped>
.el-select {
  width: 50%;
}
.select_project {
  width: 100%;
}
.buttons {
  text-align: center;
}
.twoline {
  display: flex;
  .el-form-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .el-select {
      width: 50%;
    }
  }

  justify-content: space-between;
}
.oneline {
  .el-form-item {
    width: 50%;
  }
}

</style>
